home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2009 February / PCWFEB09.iso / Software / Resources / Security / Hotspot Shield 1.08 / HSS-1.08-install-anchorfree-76-conduit.exe / components / ConduitAutoCompleteSearch.js < prev    next >
Text File  |  2008-06-26  |  13KB  |  439 lines

  1. //Helper functions and objects
  2. var EBServerDataURL = 
  3. {
  4.     ServerRequest : function(strURL,strPostData,strUserName,strPassword,ServerResponseFunction)
  5.     {
  6.         var objIOService    = Components.classes["@mozilla.org/network/io-service;1"].createInstance(Components.interfaces.nsIIOService);
  7.         var objURI            = objIOService.newURI(strURL, null, null);
  8.         
  9.         if(strUserName != null && strPassword != null)
  10.         {
  11.             objURI.username        = strUserName;
  12.             objURI.password        = strPassword;
  13.         }
  14.         
  15.         var objChannel        = objIOService.newChannelFromURI(objURI);
  16.         
  17.         objChannel.QueryInterface(Components.interfaces.nsIHttpChannel).setRequestHeader('PRAGMA','NO-CACHE',false);
  18.         objChannel.QueryInterface(Components.interfaces.nsIHttpChannel).setRequestHeader('CACHE-CONTROL','NO-CACHE',false);
  19.  
  20.         
  21.         if(strPostData != null) 
  22.         {
  23.             var objUploadStream        = Components.classes["@mozilla.org/io/string-input-stream;1"].createInstance(Components.interfaces.nsIStringInputStream);
  24.             objUploadStream.setData(strPostData, strPostData.length);
  25.               
  26.             var objUploadChannel    = objChannel.QueryInterface(Components.interfaces.nsIUploadChannel);
  27.             objUploadChannel.setUploadStream(objUploadStream, "application/x-www-form-urlencoded", -1);
  28.               
  29.             objChannel.QueryInterface(Components.interfaces.nsIHttpChannel).requestMethod = "POST";
  30.             
  31.             
  32.         }
  33.         
  34.         
  35.         
  36.         
  37.         var objObserver = new this.Observer(ServerResponseFunction);
  38.         objChannel.asyncOpen(objObserver, null);
  39.     },
  40.     
  41.     Observer: function(ServerResponseFunction)
  42.     {
  43.         return ({
  44.                     Data : "",
  45.                     
  46.                     onStartRequest: function(aRequest, aContext)
  47.                     {
  48.                         this.Data = "";
  49.                     },
  50.                     
  51.                     onStopRequest: function(aRequest, aContext, aStatus)
  52.                     {
  53.                         if(ServerResponseFunction)
  54.                         {
  55.                             ServerResponseFunction(this.Data, aRequest);
  56.                         }
  57.                     },
  58.                         
  59.                     onDataAvailable: function(aRequest, aContext, aStream, aSourceOffset, aLength)
  60.                     {
  61.                         var objScriptableInputStream = Components.classes["@mozilla.org/scriptableinputstream;1"].createInstance(Components.interfaces.nsIScriptableInputStream);
  62.                         objScriptableInputStream.init(aStream);
  63.                         this.Data += objScriptableInputStream.read(aLength);
  64.                     }
  65.                 });
  66.     }
  67. }
  68.  
  69. function decodeUtf8(utftext) 
  70. {
  71.     var string = "";
  72.     var i = 0;
  73.     var c = c1 = c2 = 0;
  74.  
  75.     while ( i < utftext.length ) 
  76.     {
  77.  
  78.         c = utftext.charCodeAt(i);
  79.  
  80.         if (c < 128) {
  81.             string += String.fromCharCode(c);
  82.             i++;
  83.         }
  84.         else if((c > 191) && (c < 224)) {
  85.             c2 = utftext.charCodeAt(i+1);
  86.             string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
  87.             i += 2;
  88.         }
  89.         else {
  90.             c2 = utftext.charCodeAt(i+1);
  91.             c3 = utftext.charCodeAt(i+2);
  92.             string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
  93.             i += 3;
  94.         }
  95.  
  96.     }
  97.  
  98.     return string;
  99. }
  100.  
  101. function setTimeout(objDeligate, iTimeout)
  102. {
  103.     var timer = Components.classes['@mozilla.org/timer;1'].
  104.                     createInstance(Components.interfaces.nsITimer);
  105.     timer.initWithCallback(objDeligate, iTimeout, Components.interfaces.nsITimer.TYPE_ONE_SHOT); 
  106. }
  107.  
  108.  
  109. //XPCOM
  110. function ConduitAutoCompleteSearch() {
  111.     this.commands = [];
  112. }
  113.  
  114. ConduitAutoCompleteSearch.prototype = {
  115.     lastSuggetTimestamp : '',
  116.     searchString    : '',
  117.     
  118.     startSearch: function(searchString, strSuggestUrl, prevResult, listener) {
  119.         this.requestSuggestions(searchString,listener,strSuggestUrl);
  120.     },
  121.  
  122.     stopSearch: function() {
  123.     },
  124.     
  125.     requestSuggestions : function(searchString,listener,strSuggestUrl)
  126.     {
  127.         //no suggestions for this engine
  128.         this.searchString  = searchString;
  129.         if(!strSuggestUrl || !searchString)
  130.         { 
  131.             //load local history only
  132.             this.setSuggestionsAndHistory(searchString,null,listener);
  133.             return;
  134.         }
  135.         
  136.         //go get suggestions
  137.         var now = Date.parse(Date());
  138.         var arrSuggestUrl           = strSuggestUrl.split('!!');
  139.             strSuggestUrl           = arrSuggestUrl[0];
  140.         var strSearchTermToReplace  = arrSuggestUrl[1];
  141.         
  142.         strSuggestUrl = strSuggestUrl.replace(strSearchTermToReplace,escape(searchString));
  143.         var objFunc     = this;
  144.         
  145.         var oResponse   = function(strJSON)
  146.         {
  147.             objFunc.setSuggestionsAndHistory(searchString,strJSON,listener);
  148.         };
  149.         
  150.         var oRequest = 
  151.         {
  152.             originalSearchString : searchString,
  153.             
  154.             notify : function(oTimer)
  155.             {
  156.                 if(this.originalSearchString == objFunc.searchString)
  157.                     this.execute();
  158.             },
  159.             
  160.             execute : function()
  161.             {
  162.                 EBServerDataURL.ServerRequest(strSuggestUrl,null,null,null,oResponse);
  163.             },
  164.         };
  165.         
  166.         setTimeout(oRequest,300);
  167.     },
  168.  
  169.     setSuggestionsAndHistory: function(searchString,strJSON,listener) {
  170.         
  171.         var dir = null;
  172.         var bLoadHistory = true;
  173.         
  174.         try 
  175.         {
  176.             var dir = Components.classes['@mozilla.org/file/directory_service;1']
  177.                                     .createInstance(Components.interfaces.nsIProperties)
  178.                                     .get('ProfD', Components.interfaces.nsIFile);
  179.         
  180.             var sep = '/';
  181.             var path = dir.path + sep + 'EBSuggestHistory';
  182.             
  183.             try 
  184.             {
  185.                 var ebDir = Components.classes['@mozilla.org/file/local;1']
  186.                             .createInstance(Components.interfaces.nsILocalFile);
  187.                 ebDir.initWithPath(path);
  188.             }
  189.             catch(e) 
  190.             { 
  191.                 sep = '\\';
  192.                 path = dir.path + sep + 'EBSuggestHistory';
  193.                 try 
  194.                 {
  195.                     var ebDir = Components.classes['@mozilla.org/file/local;1']
  196.                                 .createInstance(Components.interfaces.nsILocalFile);
  197.                     ebDir.initWithPath(path);
  198.                 } catch(e) {}
  199.             }
  200.             
  201.             var file = Components.classes['@mozilla.org/file/local;1']
  202.                             .createInstance(Components.interfaces.nsILocalFile);
  203.             
  204.             file.initWithPath(ebDir.path + sep + 'search_history.xml');
  205.             
  206.             var data     = new String();
  207.             
  208.             var fiStream = Components.classes['@mozilla.org/network/file-input-stream;1']
  209.                     .createInstance(Components.interfaces.nsIFileInputStream);
  210.             
  211.             var siStream = Components.classes['@mozilla.org/scriptableinputstream;1']
  212.                     .createInstance(Components.interfaces.nsIScriptableInputStream);
  213.  
  214.             fiStream.init(file, 1, 0, false);
  215.             siStream.init(fiStream);
  216.             data += siStream.read(-1);
  217.             siStream.close();
  218.             fiStream.close();
  219.  
  220.             var uniConv = Components.classes['@mozilla.org/intl/scriptableunicodeconverter']
  221.                     .createInstance(Components.interfaces.nsIScriptableUnicodeConverter);
  222.             uniConv.charset = 'UTF-8';
  223.             data = uniConv.ConvertToUnicode(data);
  224.         }
  225.         catch(e) 
  226.         {
  227.             bLoadHistory = false;
  228.         }
  229.         
  230.         if(bLoadHistory)
  231.         {
  232.             var parser = Components.classes['@mozilla.org/xmlextras/domparser;1']
  233.                             .createInstance(Components.interfaces.nsIDOMParser);
  234.             
  235.             var xmlDoc        = parser.parseFromString(data, "text/xml");
  236.             
  237.             var xmlItems    = xmlDoc.documentElement.getElementsByTagName('ITEM');
  238.             
  239.             var result = [];
  240.             
  241.             var nodeValue = '';
  242.             
  243.             for(var i=0; i<xmlItems.length; i++)
  244.             {
  245.                 if(typeof (xmlItems.item(i).childNodes[0]) != "undefined")
  246.                 {
  247.                     nodeValue = xmlItems.item(i).childNodes[0].nodeValue;
  248.                     result[result.length] = nodeValue;
  249.                 }
  250.             }
  251.             
  252.             var commands = Components.classes["@mozilla.org/supports-array;1"].createInstance(Components.interfaces.nsISupportsArray);
  253.             
  254.             for (var i = 0; i < result.length; i++) 
  255.             {
  256.                 var string = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
  257.                 string.data = result[i];
  258.                 commands.AppendElement(string);
  259.             }
  260.             
  261.             var count = commands.Count();
  262.             this.commands = new Array(count);
  263.             for (var i = 0; i < count; i++)
  264.                 this.commands[i] = commands.GetElementAt(i).QueryInterface(Components.interfaces.nsISupportsString).data;
  265.             
  266.         }
  267.         
  268.         var arrSuggest = null;
  269.         
  270.         if (strJSON && strJSON.length > 0)
  271.             arrSuggest = eval("(" + strJSON + ")");
  272.             
  273.         var result = new AutoCompleteResult(searchString, this.commands, arrSuggest);
  274.         
  275.         listener.onSearchResult(this, result);
  276.     },
  277.     
  278.     QueryInterface: function (uuid) {
  279.         if (uuid.equals(Components.interfaces.nsIConduitAutoCompleteSearch) ||
  280.             uuid.equals(Components.interfaces.nsIAutoCompleteSearch) ||
  281.             uuid.equals(Components.interfaces.nsISupports)) {
  282.             return this;
  283.         }
  284.         
  285.         Components.returnCode = Components.results.NS_ERROR_NO_INTERFACE;
  286.         return null;
  287.     }
  288. }
  289.  
  290. function AutoCompleteResult(search, commands, arrSuggest) 
  291. {
  292.     var IsContains = function(arrArray, strString)
  293.     {
  294.         for(var i=0; i<arrArray.length; i++)
  295.             if(arrArray[i] == strString)
  296.                 return true;
  297.             
  298.         return false;
  299.     };
  300.     
  301.     this.search = search;
  302.     this.commands = [];
  303.     var lsearch = search.toLowerCase();
  304.     
  305.     if(commands.length > 0)
  306.     {
  307.         for (var i = 0; i < commands.length; i++) 
  308.         {
  309.             if (commands[i].toLowerCase().indexOf(lsearch) == 0)
  310.                 this.commands.push(commands[i]);
  311.         }
  312.     }
  313.     
  314.     this.HistoryStartIndex = this.commands.length;
  315.     
  316.     if(arrSuggest && search == decodeUtf8(arrSuggest[0]) && arrSuggest[1].length > 0)
  317.     {
  318.         for(var i=0; i<arrSuggest[1].length; i++)
  319.         {
  320.             if(!IsContains(this.commands ,arrSuggest[1][i])) 
  321.                 this.commands.push(decodeUtf8(arrSuggest[1][i]));
  322.         }
  323.     }
  324. }
  325.  
  326. AutoCompleteResult.prototype = {
  327.     get defaultIndex() {
  328.         return 0;
  329.     },
  330.     get errorDescription() {
  331.         return '';
  332.     },
  333.     get matchCount() {
  334.         return this.commands.length;
  335.     },
  336.     get searchResult() {
  337.         return Components.interfaces.nsIAutoCompleteResult.RESULT_SUCCESS;
  338.     },
  339.     get searchString() {
  340.         return this.search;
  341.     },
  342.     getCommentAt: function(index) {
  343.         if(index == this.HistoryStartIndex)
  344.             return this.GetCaption('suggestCaption');
  345.         else if(index == 0)
  346.             return this.GetCaption('historyCaption');
  347.         else
  348.             return '';
  349.     },
  350.     getStyleAt: function(index) {
  351.         if (!this.commands[index])
  352.            return null;  // not a category label, so no special styling
  353.      
  354.          if (index == 0)
  355.            return "suggestfirst";  // category label on first line of results
  356.      
  357.          if(index == this.HistoryStartIndex)
  358.              return "suggesthint";
  359.          
  360.          return '';
  361.     },
  362.     getValueAt: function(index) {
  363.         return this.commands[index];
  364.     },
  365.     
  366.     removeValueAt: function(rowIndex, removeFromDb) {
  367.     },
  368.     
  369.     getImageAt: function(index) {
  370.          return "";
  371.      },
  372.      
  373.      GetCaption : function(strKey)
  374.      {
  375.          var objHelper = null;
  376.          
  377.          try
  378.         {
  379.             var objHelper = Components.classes["@conduit.com/helper;3"]
  380.                                     .getService(Components.interfaces.nsIConduit);
  381.             
  382.         }
  383.         catch(e) {}
  384.         
  385.         if(objHelper)
  386.             return objHelper.retrieveKey('Common',strKey);
  387.  
  388.      },
  389.      
  390.     QueryInterface: function (uuid) {
  391.         if (uuid.equals(Components.interfaces.nsIAutoCompleteResult) ||
  392.             uuid.equals(Components.interfaces.nsISupports)) {
  393.             return this;
  394.         }
  395.         Components.returnCode = Components.results.NS_ERROR_NO_INTERFACE;
  396.         return null;
  397.     }
  398. }
  399.  
  400. const COMPONENT_ID = Components.ID("{C3123F1F-59BD-477a-977D-A55C1836A21C}");
  401.  
  402. var ConduitAutoCompleteModule = {
  403.     registerSelf: function (compMgr, fileSpec, location, type) {
  404.         compMgr = compMgr.QueryInterface(Components.interfaces.nsIComponentRegistrar);
  405.         compMgr.registerFactoryLocation(COMPONENT_ID,
  406.                                         "Conduit Auto Complete with Suggest",
  407.                                         "@mozilla.org/autocomplete/search;1?name=conduit-auto-complete-with-suggest",
  408.                                         fileSpec,
  409.                                         location,
  410.                                         type);
  411.     },
  412.  
  413.     getClassObject: function (compMgr, cid, iid) {
  414.         if (!cid.equals(COMPONENT_ID))
  415.             throw Components.results.NS_ERROR_NO_INTERFACE;
  416.         if (!iid.equals(Components.interfaces.nsIFactory))
  417.             throw Components.results.NS_ERROR_NOT_IMPLEMENTED;
  418.  
  419.         return ConduitAutoCompleteFactory;
  420.     },
  421.  
  422.     canUnload: function(compMgr) {
  423.         return true;
  424.     }
  425. };
  426.  
  427. var ConduitAutoCompleteFactory = {
  428.     createInstance: function (outer, iid) {
  429.         if (outer != null)
  430.             throw Components.results.NS_ERROR_NO_AGGREGATION;
  431.         return new ConduitAutoCompleteSearch().QueryInterface(iid);
  432.     }
  433. };
  434.  
  435. function NSGetModule(compMgr, fileSpec) {
  436.     return ConduitAutoCompleteModule;
  437. }
  438.  
  439.